import React from 'react'
import { Flex, WhiteSpace, WingBlank, NavBar, List, InputItem, Button, Toast } from 'antd-mobile'
import './login.css'
import { login } from '../api/allapi'
import { setToken } from '../serve/token'
import { setUser } from '../serve/usermsg'

class Login extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      uname: '',
      pwd: ''
    }
  }
  componentWillUnmount() {
    this.setState = state => {
      return
    }
  }
  changeInputValue = (key, val) => {
    // console.log(key, val);
    // ES6 对象的key是变量 [key]
    this.setState({
      [key]: val
    })
  }
  // 登录
  handleLogin = async () => {
    const { data, meta: { status, msg } } = await login(this.state.uname, this.state.pwd)
    if (status === 200) {
      // 如果组件是路由匹配到的，此时props会多一些东西
      // console.log(this.props);
      const { history } = this.props
      Toast.success(msg, 1);
      setToken(data.token)
      setUser({
        uid: data.uid,
        uname: data.uname
      })
      history.push('/')
    } else {
      Toast.fail(msg, 1);
    }
  }
  render() {
    return (
      <div>
        <WingBlank size='sm'>
          <Flex direction={"column"} justify={"center"}>
            <Flex.Item>
              <NavBar>登录</NavBar>
            </Flex.Item>
            <Flex.Item>
              <WhiteSpace />
              <List>
                <InputItem value={this.state.uname} onChange={val => {
                  this.changeInputValue('uname', val)
                }} placeholder="请填写姓名">姓名</InputItem>
                <InputItem value={this.state.pwd} onChange={val => {
                  this.changeInputValue('pwd', val)
                }} placeholder="请填写密码" type="password">密码</InputItem>
              </List>
              <WhiteSpace />
              <Button type="primary" onClick={this.handleLogin}>登录</Button>
            </Flex.Item>
          </Flex>
        </WingBlank>
      </div>
    )
  }
}
export default Login
